package com.softjourn.punchcard.activity;

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;

import com.actionbarsherlock.view.MenuItem;
import com.softjourn.punchcard.R;
import com.softjourn.punchcard.lib.ApiFunctions;
import com.softjourn.punchcard.lib.NetworkUtil;
import com.softjourn.punchcard.lib.SessionManager;
import com.softjourn.punchcard.model.Offer;
import com.softjourn.punchcard.model.OffersResponse;
import com.softjourn.punchcard.model.PunchCard;
import com.softjourn.punchcard.model.PunchCardsResponse;

public class MainActivity extends ExitDialogSherlockActivity {

	// Session Manager Class
	SessionManager session;

	boolean isClearSession = true;

	OffersResponse offersResponse;

	PunchCardsResponse punchCardsResponse;

	private List<Offer> offers;
	
	private PunchCard punchCard;
	
	private String clientUid;
	
	TextView mainText;

	private static final int LOGOUT_ITEM_ID = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		session = new SessionManager(MainActivity.this);
		setContentView(R.layout.activity_main);
		
		mainText = (TextView) findViewById(R.id.main_text);

		if (session.isLoggedIn()) {

			if (NetworkUtil.isConnectivityActive(getApplicationContext())) {

				Log.e("Main onCre", "On isLoggedIn");
				isClearSession = true;

				clientUid = session.getUserDetails().get(
						SessionManager.KEY_UID);

				try {
					punchCardsResponse = new PunchCardsAsyncTask().execute(clientUid)
							.get();

					offersResponse = new OffersAsyncTask().execute(clientUid).get();

					if (punchCardsResponse.getStatus().equals("OK")
							&& offersResponse.getStatus().equals("OK")
							&& punchCardsResponse.getPunchCards().size() > 0) {

						offers = offersResponse.getOffers();

						punchCard = punchCardsResponse.getPunchCards().get(0);
								
						String message = getString(R.string.main_text_mess);
						
						message = message.replace(getString(R.string.mask_username),
								session.getUserDetails().get(SessionManager.KEY_NAME));
						
						message = message.replace(getString(R.string.mask_mark_count),
								Integer.toString(punchCard.getBonuses()));
						
						mainText.setText(message);
						
						Button btnOffers = (Button) findViewById(R.id.btn_offers);
						
						btnOffers.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								new AlertDialog.Builder(v.getContext())
									.setAdapter(new OfferAdapter(v.getContext()),
											new DialogInterface.OnClickListener() {
												@Override
												public void onClick(DialogInterface dialog, int which) {
													Intent actOffer = new Intent(MainActivity.this,
															OfferActivity.class);
													
													actOffer.putExtra(Offer.class.getCanonicalName(),
															offers.get(which));
													
													actOffer.putExtra(PunchCard.class.getCanonicalName(), punchCard);
													
													startActivity(actOffer);
													
												}
											})
									.show();
							}
						});
						
						Button btnUpdateData = (Button) findViewById(R.id.btn_update_data);
						
						btnUpdateData.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								updateData();
							}
						});
						
						Button btnPurchase = (Button) findViewById(R.id.btn_purchase);
						
						btnPurchase.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								Intent actQR = new Intent(MainActivity.this, QRActivity.class);
								
								String messageQR = getString(R.string.identifier_client) + clientUid;
								
								actQR.putExtra(QRActivity.class.getCanonicalName(), messageQR);
								
								startActivity(actQR);
							}
						});
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					showAlertDialog(
							getApplicationContext(),
							getResources().getString(
									R.string.server_error_title),
							getResources().getString(
									R.string.server_error_mess), false);
					e.printStackTrace();
				}

			} else {

				// Error no internet connection
				showAlertDialog(
						getApplicationContext(),
						getResources().getString(
								R.string.no_internet_connection_title),
						getResources().getString(
								R.string.no_internet_connection_mess), false);

			}
		} else {
			Log.e("Main onCre", "On login");
			Intent login = new Intent(MainActivity.this, LoginActivity.class);

			startActivity(login);
			isClearSession = false;
			finish();
		}
	}
	
	private void updateData() {
		try {
			punchCardsResponse = new PunchCardsAsyncTask().execute(clientUid)
					.get();

			offersResponse = new OffersAsyncTask().execute(clientUid).get();

			if (punchCardsResponse.getStatus().equals("OK")
					&& offersResponse.getStatus().equals("OK")
					&& punchCardsResponse.getPunchCards().size() > 0) {

				offers = offersResponse.getOffers();

				punchCard = punchCardsResponse.getPunchCards().get(0);
				
				String message = getString(R.string.main_text_mess);
				
				message = message.replace(getString(R.string.mask_username),
						session.getUserDetails().get(SessionManager.KEY_NAME));
				
				message = message.replace(getString(R.string.mask_mark_count),
						Integer.toString(punchCard.getBonuses()));
				
				mainText.setText(message);
				
			}
			
		} catch(Exception e) {

			showAlertDialog(
					getApplicationContext(),
					getResources().getString(
							R.string.server_error_title),
					getResources().getString(
							R.string.server_error_mess), false);
			e.printStackTrace();
		}
		
	}
	
	@Override
	public void onResume() {
		
		super.onResume();
		updateData();
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(0, LOGOUT_ITEM_ID, LOGOUT_ITEM_ID, R.string.logout)
				.setShowAsAction(
						MenuItem.SHOW_AS_ACTION_ALWAYS
								| MenuItem.SHOW_AS_ACTION_WITH_TEXT);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case LOGOUT_ITEM_ID:

			logOut();
			return true;

		}

		return false;
	}

	private void logOut() {

		Log.e("Main onCre", "On login");

		if (isClearSession) {
			session.clearSessionData();

			Intent login = new Intent(MainActivity.this, LoginActivity.class);
			// login.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY );

			startActivity(login);

			finish();
		}
	}

	private class PunchCardsAsyncTask extends
			AsyncTask<String, Void, PunchCardsResponse> {

		@Override
		protected PunchCardsResponse doInBackground(String... params) {

			ApiFunctions userFunction = new ApiFunctions(MainActivity.this);
			try {
				PunchCardsResponse response = userFunction
						.punchCards(params[0]);
				Log.i("OK", response.toString());
				return response;

			} catch (Exception e) {
				Log.e("EXCEPTION", e.getMessage());
			}

			return null;
		}
	}

	private class OffersAsyncTask extends
			AsyncTask<String, Void, OffersResponse> {

		@Override
		protected OffersResponse doInBackground(String... params) {

			ApiFunctions userFunction = new ApiFunctions(MainActivity.this);
			try {
				OffersResponse response = userFunction.offers(params[0]);
				Log.i("OK", response.toString());
				return response;

			} catch (Exception e) {
				Log.e("EXCEPTION", e.getMessage());
			}

			return null;
		}

	}

	private class OfferAdapter extends BaseAdapter {
		private Context mContext;
		
		public OfferAdapter(Context c) {
			mContext = c;
		}
		
		public int getCount() {
			return offers.size();
		}
		
		public Object getItem(int position) {
			return null;
		}
		
		public long getItemId(int position) {
			return 0;
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
			LinearLayout layout;
			
			layout = new LinearLayout(mContext);
			
			layout.setLayoutParams(new ListView.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
			
			layout.setOrientation(LinearLayout.VERTICAL);
			layout.setBackgroundResource(R.drawable.offer_selector_punchcard);
			layout.setPadding(10, 5, 5, 10);
			
			TextView offerName = new TextView(mContext);
			
			offerName.setText(offers.get(position).getName());
			offerName.setTextColor(getResources().getColor(R.color.blue_text));
			
			TextView offerPrice = new TextView(mContext);
			
			String price = getString(R.string.offer_price);
			price = price.replace(getString(R.string.mask_mark_count),
					Integer.toString(offers.get(position).getBonuses()));
			
			offerPrice.setText(price);
			offerPrice.setTextColor(getResources().getColor(R.color.blue_text));
			
			layout.addView(offerName);
			layout.addView(offerPrice);
			
			return layout;
		}
	}
}
